package com.lxb.Back_Mysql.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Configuration
@EnableScheduling
@RestController
@RequestMapping("/RunShell")
public class ShellController {

    /**
     * 定时器每天凌晨执行脚本
     *
     */
    //每天凌晨0点备份,执行调用脚本
    @Scheduled(cron = "0 0 0 * * ?")
    @RequestMapping("/run")
    public List<String> DaoShell(){

        //String path = "/data/mysql_bak/mysql_bak.sh";
        //当前项目的绝对路径
        File f = new File("");
        //拼接存放脚本的文件夹
        String path = f.getAbsolutePath()+"/config/mysql_bak.sh";
        System.out.println(path+"-------------");
        //调用脚本执行方法
        List<String> list = ShellController.exceShell(path);
        return list;
    }


    /**
     * 执行脚本方法
     *
     * @return
     */
    public static List<String> exceShell(String pathOrCommand) {
        List<String> result = new ArrayList<>();
        try {
            log.info("----执行完全数据库备份----");
            // 执行脚本
            Process ps = Runtime.getRuntime().exec(pathOrCommand);
            log.info("开始执行时间 = " + new Date());
            int exitValue = ps.waitFor();
            if (0 != exitValue) {
                log.info("call shell failed. error code is :" + exitValue);
            }

            // 只能接收脚本echo打印的数据，并且是echo打印的最后一次数据
            BufferedInputStream in = new BufferedInputStream(ps.getInputStream());
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String line;
            while ((line = br.readLine()) != null) {
                log.info("脚本返回的数据如下： " + line);
                result.add(line);
            }
            in.close();
            br.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("结束执行时间 = " + new Date());
        return result;
    }
}



